//###############
//FILE : QuitCommand.java
//WRITER : Daniel Lowengrub, daniel_i_l, 320687098
//EXERCISE : oop ex3 2011
//DESCRIPTION:
//See below
//###############
package oop.ex3.filemanager;

import oop.ex3.communication.ServerStatus;
import oop.ex3.communication.SocketAddress;
import oop.ex3.protocol.sessions.FileGoodByeSession;

/**
 *  Implements the QUIT command as specified in the assignment.
 * @author daniel
 */
public class QuitCommand extends UserCommand{
    private static final String QUIT_COMMAND = "QUIT";
    private static final String QUIT_MESSAGE = "Bye-bye!";
    private NameServerConnection _connection;
    private NameServerDatabase _nameServers;
    private ServerStatus _requestStatus;

    /**
     * Construct a quit command with a connection used for communication with
     * NSs and a server status instance used for changing the status (closing) of the FS.
     * @param connection The connection to use.
     * @param status The status of the FS we want to close.
     */
    public QuitCommand(NameServerConnection connection, ServerStatus status) {
        super(QUIT_COMMAND);
        _connection = connection;
        _nameServers = connection.getNameServerDatabase();
        _requestStatus = status;
    }

    private void notifyServer(SocketAddress nameServer) {
        if (!_connection.initializeStreams(nameServer))
            return;
        
        FileGoodByeSession goodBye = new FileGoodByeSession();
        _connection.initializeSession(goodBye);
        _connection.executeSession(goodBye);
        
        _connection.closeConnection();
    }

    @Override
    public boolean executeCommand(String command) {

        //System.out.println("quitting");
        //close request thread
        _requestStatus.stopServer();

        //notify servers
        for (SocketAddress nameServer : _nameServers.getAddressList())
            notifyServer(nameServer);

        //and stop user thread
        System.out.println(QUIT_MESSAGE);
        
        return false;
    }


}
